package com.apes.fn.pi.permit;

import afu.org.checkerframework.checker.units.qual.A;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.outbox.annotation.OutboxSubscriber;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.EventUtil;
import com.apes.framework.util.MapUtil;
import com.apes.framework.util.Tools;
import com.apes.hr.base.model.Employee;
import com.apes.hr.base.repository.EmployeeRepository;
import com.apes.hr.paySupport.model.SupportApplication;
import com.apes.hr.paySupport.model.SupportApplicationExecution;
import com.apes.hr.paySupport.repository.SupportApplicationExecutionRepository;
import com.apes.hr.paySupport.repository.SupportApplicationRepository;
import com.apes.hr.transfer.model.TransferApplication;
import com.apes.hr.transfer.repository.TransferApplicationRepository;
import com.apes.scm.masterdata.area.model.Area;
import com.apes.scm.masterdata.area.repository.AreaRepository;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.frame.model.Branch;
import com.apes.scm.masterdata.frame.model.Dept;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.BranchRepository;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.pi.service.PiManager;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.AccessProvider;
import com.apes.scm.masterdata.party.model.Corporate;
import com.apes.scm.masterdata.party.model.Party;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.party.repository.AccessProviderRepository;
import com.apes.scm.masterdata.party.repository.CorporateRepository;
import com.apes.scm.masterdata.party.repository.PartyRepository;
import com.apes.scm.masterdata.party.repository.PartyRoleRepository;
import com.apes.scm.rbac.model.*;
import com.apes.scm.rbac.repository.*;
import com.apes.scm.rbac.service.LocalPermitService;
import com.apes.scm.rbac.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @ClassName permitService
 * @Description TODO
 * @Author pengyb
 * @Date 2019/12/12 9:54
 * @Version 1.0
 **/
@Service("permitService")
public class PermitService extends DomainService {
    @Autowired
    AccessProviderRepository accessProviderRepository;
    @Autowired
    UserRepository userRepository;
    @Autowired
    LocalPermitRepository localPermitRepository;
    @Autowired
    LocalPermitService localPermitService;
    @Autowired
    RoleRepository roleRepository;
    @Autowired
    MenuRepository menuRepository;
    @Autowired
    PostRepository postRepository;
    @Autowired
    DeptRepository deptRepository;
    @Autowired
    UserService userService;
    @Autowired
    PiManager piManager;
    @Autowired
    PartyRoleRepository partyRoleRepository;
    @Autowired
    PartyRepository partyRepository;
    @Autowired
    CorporateRepository corporateRepository;
    @Autowired
    StoreRepository storeRepository;
    @Autowired
    EmployeeRepository employeeRepository;
    @Autowired
    TransferApplicationRepository transferApplicationRepository;
    @Autowired
    LocalPermitItemRepository localPermitItemRepository;
    @Autowired
    SupportApplicationRepository supportApplicationRepository;
    @Autowired
    EnumerationRepository enumerationRepository;
    @Autowired
    SupportApplicationExecutionRepository supportApplicationExecutionRepository;
    @Autowired
    BranchRepository branchRepository;
    /**
     * String --> Date
     * @param date
     * @param dateFormat
     * @return
     */
    public String DateToString( Date date, String dateFormat){
        DateFormat format = new SimpleDateFormat(dateFormat);
        String dateString = format.format(date);
        return dateString;
    }

    /**
     * App同步接入商的查询接口
     *
     * @param request
     * @return
     */
    public List<Map> synAccessProviderToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<AccessProvider> accessProviderList = accessProviderRepository.findByLastUpdatedStampAndId(date, id, PageRequest.of(0, maxNum));
        List<Map> listMap = new ArrayList<>();
        accessProviderList.stream().forEach(accessProvider -> {
            Map map = new HashMap();
            map.put("id",accessProvider.getId());
            map.put("name",accessProvider.getName());
            map.put("lastUpdatedStamp",DateToString(accessProvider.getLastUpdatedStamp(),"yyyy-MM-dd HH:mm:ss.SSS"));
            map.put("note",accessProvider.getNote());
            map.put("actualController",accessProvider.getActualController());
            JSONArray array = new JSONArray();
            accessProvider.getCompanys().forEach(company->{
                JSONObject object = new JSONObject();
                object.put("id",company.getId());
                object.put("name",company.getName());
                object.put("officeCity",company.getParty().getCorporate().getOfficeCity());
                object.put("officeProvince",company.getParty().getCorporate().getOfficeProvince());
                object.put("officeCounty",company.getParty().getCorporate().getOfficeCounty());
                object.put("settlementCenter", company.getParty().isSettlementCenter());
                array.add(object);
            });
            map.put("companys",array);
            listMap.add(map);
        });
        return listMap;
    }


    /**
     * App同步单位客户的查询接口
     *
     * @param request
     * @return
     */
    public List<Map> synCorporateCustomToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<PartyRole> corporateCustomList = partyRoleRepository.findByLastUpdatedStampAndId("corporate","Customer",date, id, PageRequest.of(0, maxNum));
        List<Map> listMap = new ArrayList<>();
        corporateCustomList.stream().forEach(corporateCustom -> {
            Party party = corporateCustom.getParty();
            Corporate corporate = party.getCorporate();
            Map map = new HashMap();
            map.put("id",corporateCustom.getId());
            map.put("name",corporateCustom.getName());
            map.put("lastUpdatedStamp",DateToString(corporateCustom.getLastUpdatedStamp(),"yyyy-MM-dd HH:mm:ss.SSS"));
            map.put("createDate",String.valueOf(corporateCustom.getCreateDate()));
            map.put("updateDate",String.valueOf(corporateCustom.getUpdateDate()));
            if (corporate!=null){
                map.put("valid",corporate.isValid());
                map.put("officeCounty",corporate.getOfficeCounty());
                map.put("officeProvince",corporate.getOfficeProvince());
                map.put("officeCity",corporate.getOfficeCity());
                map.put("officeCountry",corporate.getOfficeCountry());
                map.put("officeAddress",corporate.getOfficeAddress());
                map.put("customerGroup",corporate.getCustomerGroup());
                map.put("companyNature",corporate.getCompanyNature());
            }
            map.put("invoicePhone",party.getInvoicePhone());
            PartyRole role = partyRoleRepository.findByPartyIdAndRoleId(corporateCustom.getParty().getId(),"Company");
            if (role!=null){
                map.put("companyId",role.getId());
                AccessProvider accessProvider = role.queryAccessProvider();
                if (accessProvider!=null){
                    map.put("accessProviderId",accessProvider.getId());
                    map.put("accessProviderName",accessProvider.getName());
                }
            }
            listMap.add(map);
        });
        return listMap;
    }

    public List<Map> accessProviderToMap( List<AccessProvider> accessProviderList){
        List<Map> mapList = new ArrayList<>();
         accessProviderList.stream().forEach(accessProvider -> {
           Map map = Tools.toMap(accessProvider);
           JSONArray jsonArray = new JSONArray();
           jsonArray.add(map.get("companys"));
             jsonArray.stream().forEach(company -> {
                 Map comMap = MapUtil.mapped(company);
                 Corporate corporate = partyRoleRepository.findOne((String) comMap.get("id")).getParty().getCorporate();
                 jsonArray.add(comMap.put("corporate",corporate));
            });
            mapList.add(map);
        });
        return mapList;
    }
    /**
     * App同步操作员的全量查询接口
     *
     * @param request
     * @return
     */
    public List<User> synUserToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<User> userList = userRepository.findByLastUpdatedStampAndId(date, id, PageRequest.of(0, maxNum));
        return userList;

    }


    /**
     * App同步本地权限的全量查询接口
     *
     * @param request
     * @return
     */
    public List<LocalPermit> synLocalPermitToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<LocalPermit> localPermitList = localPermitRepository.findByLastUpdatedStampAndId(date, id, PageRequest.of(0, maxNum));
        localPermitList.forEach(localPermit -> {
            // 转换成Map
            this.convertLocalPermitItemsToPurposeMap(localPermit);
        });

        return localPermitList;
    }
    /*
     * LocalPermitItem 转换成权限Map
     * */
    private void convertLocalPermitItemsToPurposeMap(LocalPermit localPermit) {
        Optional.ofNullable(localPermit).ifPresent(
                (loP) -> {
                    localPermit.setPermitPurposeBelong(getPermitPurposeMap(localPermit.getLocalPermitItems(),"pp_belong"));
                    localPermit.setPermitPurposeOperate(getPermitPurposeMap(localPermit.getLocalPermitItems(),"pp_operate"));
                    localPermit.setPermitPurposeSearch(getPermitPurposeMap(localPermit.getLocalPermitItems(),"pp_search"));
                }
        );

    }
    /*
     * 获取对应权限（所属、操作、查询）前端需要的格式
     * */
    private JSONObject getPermitPurposeMap(Set<LocalPermitItem> localPermitItems, String purpose) {
        if(localPermitItems ==  null)  return  null;
        JSONObject permitPurposeMap = new JSONObject();
        List<Map> company = new ArrayList<>();
        List<Map> dept = new ArrayList<>();
        List<Map> location = new ArrayList<>();
        localPermitItems.stream().filter(
                (LocalPermitItem item) -> {
                    return  item.getPurpose().getId().equals(purpose);
                }
        ).forEach(
                (LocalPermitItem item) -> {
                    Map result = new HashMap();
                    result.put("id",item.getOrgId());
                    result.put("name",item.getOrgName());
                    if(item.getType().getId().equals("pt_company")) {  // 公司
                        Party party = partyRoleRepository.findOne(item.getOrgId()).getParty();
                        result.put("operation",Optional.ofNullable(corporateRepository.findByParty(party).getOperation()).orElse(new Enumeration()).getDescription());
                        company.add(result);
                    } else if (item.getType().getId().equals("pt_dept")) {  // 部门
                        dept.add(result);
                    } else if (item.getType().getId().equals("pt_location")) { // 仓库
                        location.add(result);
                    }
                }
        );
        permitPurposeMap.put("pt_company",company);
        permitPurposeMap.put("pt_dept",dept);
        permitPurposeMap.put("pt_location",location);
        return permitPurposeMap;
    }



    /**
     * App同步通用角色的全量查询接口
     *
     * @param request
     * @return
     */
    public List<Role> synRoleToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<Role> roleList = roleRepository.findByLastUpdatedStampAndId(date, id, PageRequest.of(0, maxNum));
        roleList.forEach(role -> {
            role.setOptList(getOptList(role));
        });
        return roleList;
    }
    private Set<Map> getOptList(Role role) {
        if (role.getOperations() == null) return null;
        Set operations = new HashSet<>();
        role.getOperations().forEach(op -> {
            Map row = MapUtil.mapper("menu_id", op.getMenu().getId(),
                    "operationId",op.getOperationId());
            operations.add(row);
        });
        return operations;
    }

    /**
     * App同步菜单的全量查询接口
     *
     * @param request
     * @return
     */
    public List<Menu> synMenuToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        int id = jsonObject.getInteger("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<Menu> menuList = menuRepository.findByLastUpdatedStampAndId(date, id, PageRequest.of(0, maxNum));
        return menuList;

    }


    /**
     * App同步本地角色的全量查询接口
     *
     * @param request
     * @return
     */
    public List<Post> synPostToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<Post> postList = postRepository.findByLastUpdatedStampAndId(DateUtil.format(date,"yyyy-MM-dd HH:mm:ss.SSS"), id, PageRequest.of(0, maxNum));
        return postList;

    }

    /**
     * App同步本地角色的全量查询接口
     *
     * @param request
     * @return
     */
    public List<Dept> synDeptToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("id");
        int maxNum = jsonObject.getInteger("maxNum");
        Date date = new Date(jsonObject.getLong("timestamp"));
        List<Dept> deptList =  deptRepository.findByLastUpdatedStampAndId(DateUtil.format(date,"yyyy-MM-dd HH:mm:ss.SSS"), id, PageRequest.of(0, maxNum));
        return deptList;

    }
    /**
     * App同步门店信息的全量查询接口
     * @param request
     * @return
     */
    public List synStoreToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        String id = jsonObject.getString("id"); //  最后更新ID
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数
        List<Store> storeList = storeRepository.findAllStoreByTs(DateUtil.format(timestamp,"yyyy-MM-dd HH:mm:ss.SSS"), id, PageRequest.of(0, maxNum));
        List<Map> listMap = new ArrayList<>();
        storeList.stream().forEach(store -> {
            Map map = MapUtil.mapper("store", store);
            AccessProvider accessProvider = accessProviderRepository.findByCompany(store.getCompany().getId());
            Corporate corporate = store.getCompany().getParty().getCorporate();
            String description = corporate.getOperation().getDescription();
            map.put("operation",description);
            if (accessProvider!=null){
                map.put("accessProviderId",accessProvider.getId());
                map.put("accessProviderName",accessProvider.getName());
            }
            listMap.add(map);

        });
        return listMap;

    }

    /**
     * App  手机号 登陆调用的
     *
     * @param request
     * @return
     */
    public Map loginByAppMobileNumber(SimpleRequest request) {
        String mobileNumber = request.get("mobileNumber");
        User user = userRepository.findByMobileNumber(mobileNumber);
        if (user == null) throw new RuntimeException("此用户不存在!");
        return userService.login(request);
    }

    /**
     * App 登陆调用
     *
     * @param request
     * @return
     */
    public Map loginByApp(SimpleRequest request) {
        return userService.login(request);
    }

    /**
     * App 菜单保存调用
     *
     * @param request
     * @return
     */
    public Menu synAppToMenuSave(SimpleRequest request) {
        Menu menu = request.getO(Menu.class);
        Enumeration enumeration = new Enumeration();
        enumeration.setId("app");
        menu.setTerminalType(enumeration);
        Enumeration groupType = new Enumeration();
        groupType.setId("merchant");
        menu.setGroupType(groupType);
        menu.setPath(menu.localPath());
        return menuRepository.saveAndFlush(menu);
    }

    /**
     * App 菜单删除调用
     *
     * @param request
     * @return
     */
    public String synAppToMenuDelete(SimpleRequest request) {
        Menu menu = request.getO(Menu.class);
        menuRepository.delete(menu.getId());
        return "删除成功";
    }

    public void synMenuSaveToApp(SimpleRequest request) {
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synMenuToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synMenuDeleteToApp(SimpleRequest request) {
        Menu menu = request.getO(Menu.class);
        piManager.synApp("", mapper(menu));
    }

    /**
     * App 本地权限保存调用
     *
     * @param request
     * @return
     */
    public LocalPermit synAppToLocalPermitSave(SimpleRequest request) {
        LocalPermit localPermit = request.getO(LocalPermit.class);
        return localPermitRepository.saveAndFlush(localPermit);
    }

    /**
     * App 本地权限删除调用
     *
     * @param request
     * @return
     */
    public String synAppToLocalPermitDelete(SimpleRequest request) {
        LocalPermit localPermit = request.getO(LocalPermit.class);
        localPermitRepository.delete(localPermit.getId());
        return "删除成功";
    }

    /**
     * 通过调用app通知接口
     * @param request
     */
    public void synLocalPermitSaveToApp(SimpleRequest request) {
//        LocalPermit localPermit = request.getO(LocalPermit.class);
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synLocalPermitToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synLocalPermitDeleteToApp(SimpleRequest request) {
        LocalPermit localPermit = request.getO(LocalPermit.class);
        piManager.synApp("", mapper(localPermit));
    }

    /**
     * App 本地角色保存调用
     *
     * @param request
     * @return
     */
    public Post synAppToPostSave(SimpleRequest request) {
        Post post = request.getO(Post.class);
        return postRepository.saveAndFlush(post);
    }

    /**
     * App 本地角色删除调用
     *
     * @param request
     * @return
     */
    public String synAppToPostDelete(SimpleRequest request) {
        Post post = request.getO(Post.class);
        postRepository.delete(post.getId());
        return "删除成功";
    }

    public void synPostSaveToApp(SimpleRequest request) {
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synPostToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synPostDeleteToApp(SimpleRequest request) {
        Post post = request.getO(Post.class);
        piManager.synApp("", mapper(post));
    }


    /**
     * App 本地角色保存调用
     *
     * @param request
     * @return
     */
    public Role synAppToRoleSave(SimpleRequest request) {
        Role role = request.getO(Role.class);
        return roleRepository.saveAndFlush(role);
    }

    /**
     * App 本地角色删除调用
     *
     * @param request
     * @return
     */
    public String synAppToRoleDelete(SimpleRequest request) {
        Role role = request.getO(Role.class);
        roleRepository.delete(role.getId());
        return "删除成功";
    }

    public void synRoleSaveToApp(SimpleRequest request) {
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synRoleToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synRoleDeleteToApp(SimpleRequest request) {
        Role role = request.getO(Role.class);
        piManager.synApp("", mapper(role));
    }


    public void synUserSaveToApp(SimpleRequest request) {
        User user = request.getO(User.class);
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synUserToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synStoreSaveToApp(SimpleRequest request) {
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synStoreToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synUserDeleteToApp(SimpleRequest request) {
        User user = request.getO(User.class);
        piManager.synApp("", mapper(user));
    }

    public List<Area> findAllArea(SimpleRequest request) {
        List<Area> areaList = SpringManager.getBean(AreaRepository.class).findAll();
        return areaList;
    }

    /**
     * App同步人员信息的全量查询接口
     * @param request
     * @return
     */
    public List synEmployeeToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        String id = jsonObject.getString("id"); // 最后更新ID
        int maxNum = jsonObject.getInteger("maxNum"); // 单次请求最大条数
        List<Employee> employeeList = employeeRepository.findAllEmployeeByTs(DateUtil.format(timestamp,"yyyy-MM-dd HH:mm:ss.SSS"), id, PageRequest.of(0, maxNum));
        List<Map> listMap = new ArrayList<>();
        employeeList.stream().forEach(employee -> {
            Map map = MapUtil.mapped(employee);
            if (employee.getCompany()!=null){
                AccessProvider accessProvider = accessProviderRepository.findByCompany(employee.getCompany().getId());
                if (accessProvider!=null){
                    map.put("accessProviderId",accessProvider.getId());
                    map.put("accessProviderName",accessProvider.getName());
                }
            }
            if (employee.getParty()!=null){
                PartyRole partyRole = partyRoleRepository.findByPartyIdAndRoleId(employee.getParty().getId() ,"Employee");
                List<User> userList = userRepository.findByPartyRole(partyRole);
                if (!userList.isEmpty()){
                    map.put("user",userList.get(0));
                }
            }
            List<Post> postList = postRepository.findAllByBranchAndWorkPost(employee.getWorkBranch(),employee.getPost());
            if (!postList.isEmpty()){
                List<LocalPermitItem> localPermitItemList = localPermitItemRepository.find(postList.get(0).getId(),"pp_belong","pt_dept");
                if (!localPermitItemList.isEmpty()){
                    map.put("dept",localPermitItemList.get(0).getOrgId());
                    map.put("deptName",localPermitItemList.get(0).getOrgName());
                }
            }
            Branch workBranch = employee.getWorkBranch();
            if(workBranch != null){
                map.put("workBranchId",workBranch.getId());
                map.put("workBranchName",workBranch.getName());
            }
            listMap.add(map);
        });
        return listMap;
    }

    /**
     * App同步行政部门的全量查询接口
     * @param request
     * @return
     */
    public List synBranchToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        String id = jsonObject.getString("id"); // 最后更新ID
        int maxNum = jsonObject.getInteger("maxNum"); // 单次请求最大条数
        List<Branch> branchList = branchRepository.findAllBranchByTs(timestamp, id, PageRequest.of(0, maxNum));
        List<Map> listMap = new ArrayList<>();
        branchList.stream().forEach(branch -> {
            Map map = MapUtil.mapped(branch);
            listMap.add(map);
        });
        return listMap;
    }

    /**
     * App同步支援单信息的全量查询接口
     * @param request
     * @return
     */
    public List synTransferApplicationToApp(SimpleRequest request) {
        JSONObject jsonObject = request.getJO();
        Date timestamp = new Date(jsonObject.getLong("timestamp"));
        String id = jsonObject.getString("id"); //  最后更新ID
        int maxNum = jsonObject.getInteger("maxNum"); //单次请求最大条数
        List<TransferApplication> applicationList = transferApplicationRepository.findAllTransferApplicationByTs(timestamp, id, PageRequest.of(0, maxNum));
        List<SupportApplication> supportApplications = supportApplicationRepository.findAllSupportApplicationByTs(timestamp, id, PageRequest.of(0, maxNum));

        List<Map> listMap = new ArrayList<>();
        applicationList.stream().forEach(transferApplication -> {
            Map map = MapUtil.mapped(transferApplication);
//            Map itemMap = (Map) map.get("transferApplicationItems");
            List<Map> itemMapList = new ArrayList<>();
            transferApplication.getTransferApplicationItems().stream().forEach(item ->{
                Map itemMap = MapUtil.mapped(item);
                PartyRole partyRole = partyRoleRepository.findByPartyIdAndRoleId( item.getTransferUid().getParty().getId() ,"Employee");
                List<User> userList = userRepository.findByPartyRole(partyRole);
                if (!userList.isEmpty()){
                    itemMap.put("user",userList.get(0));
                }

                List<Post> postList = postRepository.findAllByBranchAndWorkPost(item.getBranchAfter(),item.getWorkPostAfter());
                if (!postList.isEmpty()){
                    List<LocalPermitItem> localPermitItemList = localPermitItemRepository.find(postList.get(0).getId(),"pp_belong","pt_dept");
                    if (!localPermitItemList.isEmpty()){
                        itemMap.put("deptAfter",localPermitItemList.get(0).getOrgId());//	调动后部门
                        itemMap.put("deptAfterName",localPermitItemList.get(0).getOrgName());//	调动后部门
                    }
                }
                itemMapList.add(itemMap);
            });
            map.put("transferApplicationItems",itemMapList);
            listMap.add(map);

        });
        supportApplications.stream().forEach(supportApplication -> {
            Map map = MapUtil.mapped(supportApplication);
            List<Map> itemMapList = new ArrayList<>();
            supportApplication.getSupportApplicationItems().stream().forEach(item ->{
                Map itemMap = MapUtil.mapped(item);
                SupportApplicationExecution exec = supportApplicationExecutionRepository.findByTransferApplicationItems(item);
                PartyRole partyRole = partyRoleRepository.findByPartyIdAndRoleId(item.getSupportUid().getParty().getId() ,"Employee");
                List<User> userList = userRepository.findByPartyRole(partyRole);
                if (!userList.isEmpty()){
                    itemMap.put("user",userList.get(0));
                }
                List<Post> postList = postRepository.findAllByBranchAndWorkPost(item.getBranchAfter(),item.getWorkPostAfter());
                if (!postList.isEmpty()){
                    List<LocalPermitItem> localPermitItemList = localPermitItemRepository.find(postList.get(0).getId(),"pp_belong","pt_dept");
                    if (!localPermitItemList.isEmpty()){
                        itemMap.put("deptAfter",localPermitItemList.get(0).getOrgId());//  调动后部门
                        itemMap.put("deptAfterName",localPermitItemList.get(0).getOrgName());//  调动后部门
                    }
                }
                itemMapList.add(itemMap);
                itemMap.put("transferUid",itemMap.get("supportUid"));
                itemMap.put("effectiveDate",DateUtil.format(item.getStartDate(),"yyyy-MM-dd"));
                itemMap.put("handoverDate",DateUtil.format(item.getStartDate(),"yyyy-MM-dd"));
                itemMap.put("endDate",DateUtil.format(exec.getEndDate(),"yyyy-MM-dd"));
                itemMap.put("jobAfter",item.getSupportUid().getJob());
                itemMap.put("staffShare",item.getSupportUid().getStaffShare());
                itemMap.put("staffShareAfter",item.getSupportUid().getStaffShare());
                itemMap.put("distribution",false);
                itemMap.put("driver",item.getSupportUid().isDriver());
                itemMap.put("echelon",item.getSupportUid().isEchelon());
                itemMap.put("rankId",item.getSupportUid().getRank());
                itemMap.put("rankIdAfter",item.getSupportUid().getRank());
                itemMap.put("onDutyState",item.getSupportUid().getOnDutyState());
                itemMap.put("onDutyStateAfter",item.getSupportUid().getOnDutyState());
                itemMap.put("company",item.getSupportUid().getCompany());
                itemMap.put("transferApplications",MapUtil.mapper("id",item.getSupportApplication().getId()));

            });
            map.remove("supportApplicationDetails");

            map.put("transferApplicationItems",itemMapList);
            map.put("hrTransferType",enumerationRepository.findByTypeAndValue("支援","hrTransferType"));
            listMap.add(map);
        });
        return listMap;

    }

    public void synEmployeeSaveToApp(SimpleRequest request) {
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synEmployeeToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public void synTransferApplicationSaveToApp(SimpleRequest request) {
        Map newMap = new HashMap();
        newMap.put("method","cm.permit.synTransferApplicationToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    /**
     * 通过调用app通知接口
     * 供应商
     * @param request
     */
    public void synAccessProviderSaveToApp(SimpleRequest request) {
//        LocalPermit localPermit = request.getO(LocalPermit.class);
        Map newMap = new HashMap();
        newMap.put("method","cm.accessProvider.synAccessProviderToApp");
        newMap.put("timestamp",new Date());
        // 调用App接口 通知接口
        String notifyTopic = "event:pi.app.synAppNotify";
        JSONObject notifyFlg = (JSONObject) EventUtil.sendSynEvent(this, notifyTopic, newMap).stream().findFirst().get();

    }

    public JSONObject getCustomerByDeptId (SimpleRequest request) {
        JSONObject result = new JSONObject();
        JSONObject param = request.getJO();
        if (Objects.isNull(param.getString("deptId"))) {
            throw new RuntimeException("门店编码不能为空!!!");
        }
        Dept dept = deptRepository.findOne(param.getString("deptId"));
        Party company = dept.getCompany().getParty();
        PartyRole customer = partyRoleRepository.findByPartyIdAndRoleId(company.getId(), "Customer");
        result.put("customerId", customer.getId());
        result.put("customerName", customer.getName());
        result.put("companyId", dept.getCompany().getId());
        result.put("companyName", company.getName());
        return result;
    }

}

